

class ContentScript {
  constructor() {
    this.analytics = new AnalyticsHelper();
    this.initEventListeners();
  }

  initEventListeners() {
    // 监听页面加载
    this.analytics.trackPageView();

    // 监听滚动到底部
    window.addEventListener('scroll', () => {
      if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
        this.analytics.trackScroll();
      }
    });

    // 监听外链点击
    document.addEventListener('click', (e) => {
      const link = e.target.closest('a');
      if (link && link.hostname !== window.location.hostname) {
        this.analytics.trackOutboundClick(link.href);
      }
    });

    // 监听表单交互
    document.addEventListener('submit', (e) => {
      if (e.target.tagName === 'FORM') {
        this.analytics.trackFormInteraction(e.target.id || 'unknown_form');
      }
    });

    // 监听文件下载
    document.addEventListener('click', (e) => {
      const link = e.target.closest('a');
      if (link) {
        const extension = link.href.split('.').pop().toLowerCase();
        if (FILE_EXTENSIONS.includes(`.${extension}`)) {
          this.analytics.trackFileDownload(link.href);
        }
      }
    });

    // 监听 URL 变化以检测搜索
    const urlParams = new URLSearchParams(window.location.search);
    const searchParams = ['q', 'query', 'search', 's'];
    for (const param of searchParams) {
      if (urlParams.has(param)) {
        this.analytics.trackSiteSearch(urlParams.get(param));
        break;
      }
    }

    // 监听 YouTube 视频
    this.initYouTubeTracking();
  }

  initYouTubeTracking() {
    // 等待 YouTube API 加载
    window.onYouTubeIframeAPIReady = () => {
      document.querySelectorAll('iframe[src*="youtube.com"]').forEach(iframe => {
        new YT.Player(iframe, {
          events: {
            'onStateChange': (event) => {
              const actions = {
                0: 'complete',
                1: 'play',
                2: 'pause'
              };
              if (actions[event.data] !== undefined) {
                this.analytics.trackVideoInteraction(
                  actions[event.data],
                  iframe.src
                );
              }
            }
          }
        });
      });
    };
  }
}

new ContentScript(); 